import React, { ReactNode } from "react";
import HeaderPage from "components/header";
import styled from "@emotion/styled";
import {
  BrowserRouter as Router,
  Route,
  Redirect,
  Switch,
} from "react-router-dom";
import UserAccount from "pages/user";
import UserMember from "pages/member";
import Database from "pages/database";
import MenuPage from "components/menu";
import NoMatch from "pages/404";
import { getAuthority } from "utils/authority"

const PrivateRoute = ({ children, auth, ...rest }: {children: ReactNode, auth: string[], path: string}) => {
  const checkAuth = () => {
    const myrole = getAuthority()
    console.log('myrole', myrole)
    let result = false
    if (auth.length === 0 || auth.indexOf(myrole as any) !== -1) {
      result = true
    }
    return result
  }
  return (
    <Route
      {...rest}
      render={({ location }) =>
      checkAuth() ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: location },
            }}
          />
        )
      }
    />
  );
};

export default function AuthPage() {
  return (
    <Router>
      <HeaderPage />
      <Content>
        <LeftWrapper>
          <MenuPage />
        </LeftWrapper>
        <RigehtWrapper>
          <Switch>
            <Redirect from="/" exact to="/list" />
            <Route exact path="/list">
              <Database />
            </Route>
            <Route exact path="/user/account">
              <UserAccount />
            </Route>
            <PrivateRoute path="/user/member" auth={['admin', 'user']}>
              <UserMember />
            </PrivateRoute>
            <Route path="*">
              <NoMatch />
            </Route>
          </Switch>
        </RigehtWrapper>
      </Content>
    </Router>
  );
}

const Content = styled.div`
  height: calc(100vh - 66px);
  width: 100%;
  display: flex;
`;

const LeftWrapper = styled.div`
  width: 200px;
  height: calc(100vh - 66px);
  box-shadow: 0px 1px 4px 0px rgba(0, 21, 41, 0.12);
  background-color: #fff;
  padding-top: 32px;
  z-index: 9;
`;

const RigehtWrapper = styled.div`
  flex: 1;
  background-color: #f2f4f5;
  position: relative;
  height: calc(100vh - 65px);
  overflow: auto;
`;
